<template>
  <div class="course-choose-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>选择课程</span>
        </div>
      </template>
      
      <el-form 
        ref="formRef"
        :model="formData" 
        :rules="formRules" 
        label-width="100px"
        class="choose-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="年级" prop="grade" required>
              <el-input-number 
                v-model="formData.grade" 
                :min="2020" 
                :max="9999"
                placeholder="请输入年级（如：2024）"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专业" prop="major" required>
              <el-select 
                v-model="formData.major" 
                placeholder="请选择专业" 
                style="width: 100%;"
                :loading="majorsLoading"
                :remote-method="remoteMethod"
                :remote="true"
                :filterable="true"
                :reserve-keyword="false"
              >
                <el-option
                  v-for="major in majorsForSelect"
                  :key="major.id"
                  :label="major.name"
                  :value="major.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="课程序号">
              <el-input 
                v-model="formData.courseId" 
                placeholder="可选，直接输入课程序号"
                style="width: 100%;"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程名称">
              <el-autocomplete
                v-model="formData.courseName"
                :fetch-suggestions="queryCourseNames"
                placeholder="可选，输入课程名称"
                style="width: 100%;"
                clearable
                :trigger-on-focus="false"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" @click="handleQuery" :loading="querying">
            查询
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 查询结果 -->
    <el-card v-if="selectedCourse" class="result-card">
      <template #header>
        <div class="card-header">
          <span>已选择课程</span>
        </div>
      </template>
      
      <div class="course-info">
                 <el-descriptions :column="2" border>
           <el-descriptions-item label="年级">{{ selectedCourse.grade }}</el-descriptions-item>
           <el-descriptions-item label="专业">{{ selectedCourse.majorName || selectedCourse.major }}</el-descriptions-item>
           <el-descriptions-item label="课程序号" v-if="selectedCourse.courseId">{{ selectedCourse.courseId }}</el-descriptions-item>
           <el-descriptions-item label="课程名称" v-if="selectedCourse.courseName">{{ selectedCourse.courseName }}</el-descriptions-item>
           <el-descriptions-item label="课程ID" v-if="selectedCourse._id">{{ selectedCourse._id }}</el-descriptions-item>
         </el-descriptions>

        <!-- 毕业要求信息 -->
        <div v-if="selectedCourse.graduation_requirement" class="graduation-section">
          <h4>毕业要求信息</h4>
          <el-table :data="selectedCourse.graduation_requirement" border>
            <el-table-column prop="id" label="序号" width="80" />
            <el-table-column prop="name" label="毕业要求名称" />
            <el-table-column label="指标点" min-width="200">
              <template #default="scope">
                <div v-if="scope.row.indexPoints && scope.row.indexPoints.length > 0">
                  <div v-for="point in scope.row.indexPoints" :key="point.index_id" class="index-point">
                    <span class="index-id">{{ point.index_id }}</span>
                    <span class="index-desc">{{ point.index_desc }}</span>
                  </div>
                </div>
                <span v-else class="no-data">暂无指标点</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { courseApi } from '@/api/courseApi.js'
import { majorApi } from '@/api/majorApi.js'

// 定义props和emit
const props = defineProps({
  courseInfo: {
    type: Object,
    default: null
  },
  // 新增props用于接收外部传入的参数
  autoQueryParams: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['course-selected'])

// 响应式数据
const formRef = ref(null)
const majorsForSelect = ref([])
const majorsLoading = ref(false)
const querying = ref(false)
const selectedCourse = ref(null)

// 表单数据
const formData = reactive({
  grade: null,
  major: '',
  courseId: '',
  courseName: ''
})

// 表单验证规则
const formRules = {
  grade: [
    { required: true, message: '请输入年级', trigger: 'blur' }
  ],
  major: [
    { required: true, message: '请选择专业', trigger: 'change' }
  ]
}

// 远程模糊查询专业
const remoteMethod = async (query) => {
  if (!query) {
    majorsForSelect.value = []
    return
  }
  majorsLoading.value = true
  try {
    const res = await majorApi.fuzzyQueryMajor(query)
    majorsForSelect.value = res.data || []
  } catch (e) {
    majorsForSelect.value = []
  } finally {
    majorsLoading.value = false
  }
}

// 课程名称模糊搜索
const queryCourseNames = async (queryString, cb) => {
  if (!queryString) {
    cb([])
    return
  }
  
  try {
    const res = await courseApi.fuzzyQueryCourse(queryString)
    const courseNames = res.data || []
    const results = courseNames.slice(0, 5).map(name => ({ value: name }))
    cb(results)
  } catch (error) {
    console.error('课程名称搜索失败:', error)
    cb([])
  }
}

// 查询课程
const handleQuery = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (!formData.courseId && !formData.courseName) {
      ElMessage.warning('请填写课程序号或课程名称')
      return
    }
    
    querying.value = true
    
         const params = {
       grade: formData.grade,
       major: formData.major,
       courseId: formData.courseId || '', // 始终传递courseId参数
       courseName: formData.courseName || '' // 始终传递courseName参数
     }
    
    const result = await courseApi.selectCourse(params)
    const courseData = result.data || result
    
    if (!courseData) {
      ElMessage.error('未找到对应的课程信息')
      return
    }
    
    selectedCourse.value = courseData
    
    // 触发Vue事件通知父组件
    emit('course-selected', courseData)
    
    ElMessage.success('课程查询成功')
  } catch (error) {
    console.error('查询课程失败:', error)
    ElMessage.error('查询课程失败，请检查输入信息')
  } finally {
    querying.value = false
  }
}

// 重置表单
const handleReset = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  
  Object.assign(formData, {
    grade: null,
    major: '',
    courseId: '',
    courseName: ''
  })
  
  selectedCourse.value = null
  majorsForSelect.value = []
}

// 监听courseInfo变化，自动预选课程
watch(() => props.courseInfo, async (newCourseInfo) => {
  if (newCourseInfo && Object.keys(newCourseInfo).length > 0 && newCourseInfo.id) {
    // 自动填充表单
    formData.grade = newCourseInfo.grade || newCourseInfo.year || null
    formData.major = newCourseInfo.majorName || newCourseInfo.major || ''
    formData.courseId = newCourseInfo.courseId || newCourseInfo.id || ''
    formData.courseName = newCourseInfo.courseName || newCourseInfo.name || ''
    
    // 直接设置选中的课程
    selectedCourse.value = newCourseInfo
    
    // 触发事件通知父组件
    emit('course-selected', newCourseInfo)
  } else {
    // 如果没有有效的课程信息，清空表单和选中状态
    selectedCourse.value = null
    Object.assign(formData, {
      grade: null,
      major: '',
      courseId: '',
      courseName: ''
    })
  }
}, { immediate: true })

// 监听autoQueryParams变化，自动填充表单并查询
watch(() => props.autoQueryParams, async (newParams) => {
  if (newParams && Object.keys(newParams).length > 0) {
    // 自动填充表单
    formData.grade = newParams.grade || newParams.year || null
    formData.major = newParams.major || newParams.majorName || ''
    formData.courseId = newParams.courseId || newParams.id || ''
    formData.courseName = newParams.courseName || newParams.name || ''
    
    
    
    // 如果有足够的参数，自动触发查询
    if (formData.grade && formData.major && (formData.courseId || formData.courseName)) {
      // console.log('CourseChoose 开始自动查询...')
      // 延迟一下确保表单数据已经更新
      await nextTick()
      await handleQuery()
    } else {
      console.log('CourseChoose 参数不足，无法自动查询:', { 
        grade: formData.grade, 
        major: formData.major, 
        courseId: formData.courseId, 
        courseName: formData.courseName 
      })
    }
  }
}, { immediate: true })
</script>

<style scoped>
.course-choose-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.choose-form {
  margin-top: 20px;
}

.result-card {
  margin-top: 20px;
}

.course-info {
  margin-top: 10px;
}

.graduation-section {
  margin-top: 20px;
}

.graduation-section h4 {
  margin-bottom: 15px;
  color: #409EFF;
  font-weight: bold;
}

.index-point {
  margin-bottom: 8px;
  padding: 4px 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.index-id {
  font-weight: bold;
  color: #409EFF;
  margin-right: 8px;
}

.index-desc {
  color: #606266;
}

.no-data {
  color: #909399;
  font-style: italic;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-form-item.is-required .el-form-item__label::before) {
  content: '*';
  color: #F56C6C;
  margin-right: 4px;
}
</style>